package Serializadores;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import tp3.Tablero;

public class SerializarJugadores {
	
	public void guardarJugador(String jugador){
		
		

		try {
			//inicializo 
			File stocks = new File("jugadores.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(stocks);
			doc.getDocumentElement().normalize();
			
			
			Element tagJugador = doc.createElement(jugador);
			
			
			NodeList tagJugadores = doc.getElementsByTagName("jugadores");
			
			
			tagJugadores.item(0).appendChild(tagJugador);
			System.out.println(tagJugadores.item(0).getFirstChild().getNodeName());
			
		
		
		
			
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File("jugadores.xml"));

			transformer.transform(source, result);
			}
			catch (TransformerException tfe) {
			tfe.printStackTrace();
		  	
			} catch (Exception ex) {
			ex.printStackTrace();

			}


	}
	
	public List<String> listaJugadores(){
		
		
		
		
		
		try {
			List<String> jugadores = new ArrayList<String>();
			//inicializo 
			File stocks = new File("jugadores.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(stocks);
			doc.getDocumentElement().normalize();
			
			
			
			NodeList nodes = doc.getElementsByTagName("jugadores");
			NodeList tagJugadores = nodes.item(0).getChildNodes();
			
			
			for (int i = 0;  i < tagJugadores.getLength() ; i++){
				
				jugadores.add(tagJugadores.item(i).getNodeName());
				
				
				
			}
			
			
			
			 
			 return jugadores;
			} catch (Exception ex) {
			ex.printStackTrace();
			
			return null;
			
			}
		
		
		
		
	}
	
}
